package com.github.cyf.filter;

import com.github.cyf.common.util.MDCUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author chenyifan
 * @create 2024-09-02 17:32
 */
@Component
@Slf4j
@WebFilter(urlPatterns = "/*", filterName = "MdcFilter")
public class MdcFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String traceId = httpServletRequest.getHeader(MDCUtil.TRACE_ID);
        if (traceId != null) {
            MDCUtil.setTraceId(traceId);
        } else {
            MDCUtil.setDefaultTraceId();
        }
        chain.doFilter(request, response);
        MDCUtil.clear();
    }

}